<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Monitor SDK 测试页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.2rem;
            opacity: 0.9;
        }

        .card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }

        .card h2 {
            color: #333;
            margin-bottom: 15px;
            font-size: 1.5rem;
        }

        .button-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }

        .btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            min-width: 120px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn.danger {
            background: linear-gradient(45deg, #ff6b6b, #ee5a52);
        }

        .btn.success {
            background: linear-gradient(45deg, #51cf66, #40c057);
        }

        .btn.warning {
            background: linear-gradient(45deg, #ffd43b, #fab005);
        }

        .output {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 13px;
            line-height: 1.5;
            max-height: 300px;
            overflow-y: auto;
            white-space: pre-wrap;
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .status-item {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .status-item h3 {
            color: #333;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .status-item .value {
            font-size: 18px;
            font-weight: bold;
            color: #667eea;
        }

        .demo-area {
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin: 15px 0;
            background: #f8f9fa;
        }

        .demo-area input {
            padding: 8px 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            margin: 5px;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 Web Monitor SDK</h1>
            <p>企业级前端监控系统测试页面</p>
        </div>

        <!-- 监控状态 -->
        <div class="card">
            <h2>📊 监控状态</h2>
            <div class="status-grid">
                <div class="status-item">
                    <h3>SDK状态</h3>
                    <div class="value" id="sdk-status">未初始化</div>
                </div>
                <div class="status-item">
                    <h3>会话ID</h3>
                    <div class="value" id="session-id">-</div>
                </div>
                <div class="status-item">
                    <h3>用户ID</h3>
                    <div class="value" id="user-id">未设置</div>
                </div>
                <div class="status-item">
                    <h3>采集器数量</h3>
                    <div class="value" id="collectors-count">0</div>
                </div>
            </div>
            
            <div class="button-group">
                <button class="btn success" onclick="initSDK()">🚀 初始化SDK</button>
                <button class="btn" onclick="getStatus()">📊 查看状态</button>
                <button class="btn warning" onclick="toggleDebug()">🔍 切换调试</button>
                <button class="btn" onclick="flushData()">📤 立即上报</button>
            </div>
        </div>

        <!-- 错误监控测试 -->
        <div class="card">
            <h2>❌ 错误监控测试</h2>
            <div class="button-group">
                <button class="btn danger" onclick="triggerJSError()">💥 JS错误</button>
                <button class="btn danger" onclick="triggerPromiseError()">🔄 Promise错误</button>
                <button class="btn danger" onclick="triggerResourceError()">📁 资源错误</button>
                <button class="btn danger" onclick="triggerCustomError()">🎯 自定义错误</button>
            </div>
        </div>

        <!-- 性能监控测试 -->
        <div class="card">
            <h2>⚡ 性能监控测试</h2>
            <div class="button-group">
                <button class="btn" onclick="measurePerformance()">📏 性能测量</button>
                <button class="btn" onclick="simulateSlowTask()">🐌 慢任务模拟</button>
                <button class="btn" onclick="getWebVitals()">📊 Web Vitals</button>
                <button class="btn" onclick="testMemoryUsage()">💾 内存测试</button>
            </div>
        </div>

        <!-- 网络监控测试 -->
        <div class="card">
            <h2>🌐 网络监控测试</h2>
            <div class="button-group">
                <button class="btn" onclick="testFetch()">🔄 Fetch请求</button>
                <button class="btn" onclick="testXHR()">📡 XHR请求</button>
                <button class="btn" onclick="testSlowAPI()">🐌 慢请求</button>
                <button class="btn danger" onclick="testFailedAPI()">❌ 失败请求</button>
            </div>
        </div>

        <!-- 用户行为测试 -->
        <div class="card">
            <h2>👤 用户行为测试</h2>
            <div class="demo-area">
                <p>在下面区域进行交互，监控系统会自动记录您的行为：</p>
                <button class="btn" onclick="trackClick(this)">点击测试</button>
                <input type="text" placeholder="输入测试" onchange="trackInput(this)">
                <div style="height: 100px; overflow-y: scroll; border: 1px solid #ccc; margin: 10px 0; padding: 10px;">
                    <p>滚动测试区域</p>
                    <p>这是一个可滚动的区域</p>
                    <p>滚动行为会被自动监控</p>
                    <p>继续滚动...</p>
                    <p>更多内容...</p>
                    <p>底部内容</p>
                </div>
            </div>
        </div>

        <!-- 自定义事件测试 -->
        <div class="card">
            <h2>🎯 自定义事件测试</h2>
            <div class="button-group">
                <button class="btn" onclick="trackBusinessEvent()">💼 业务事件</button>
                <button class="btn" onclick="trackUserAction()">👤 用户行为</button>
                <button class="btn" onclick="setUserInfo()">📝 设置用户信息</button>
                <button class="btn" onclick="setMetadata()">🏷️ 设置元数据</button>
            </div>
        </div>

        <!-- 输出日志 -->
        <div class="card">
            <h2>📋 实时日志</h2>
            <div class="output" id="output"></div>
            <div style="margin-top: 10px;">
                <button class="btn" onclick="clearOutput()">🗑️ 清空日志</button>
                <button class="btn" onclick="exportLogs()">💾 导出日志</button>
            </div>
        </div>
    </div>

    <script>
        // 日志输出函数
        function log(message, type = 'info') {
            const output = document.getElementById('output');
            const timestamp = new Date().toLocaleTimeString();
            const icon = {
                info: 'ℹ️',
                success: '✅',
                error: '❌',
                warning: '⚠️'
            }[type] || 'ℹ️';
            
            const logEntry = `[${timestamp}] ${icon} ${message}\n`;
            output.textContent += logEntry;
            output.scrollTop = output.scrollHeight;
            
            // 同时输出到控制台
            console.log(logEntry);
        }

        // 更新状态显示
        function updateStatus() {
            try {
                // 这里需要实际的监控SDK状态
                document.getElementById('sdk-status').textContent = '已初始化';
                document.getElementById('session-id').textContent = 'session_' + Date.now();
                document.getElementById('user-id').textContent = 'test_user';
                document.getElementById('collectors-count').textContent = '4';
            } catch (error) {
                log('更新状态失败: ' + error.message, 'error');
            }
        }

        // SDK初始化
        function initSDK() {
            log('正在初始化 Web Monitor SDK...', 'info');
            
            try {
                // 模拟SDK初始化
                log('SDK初始化成功！', 'success');
                log('- 错误采集器已启动', 'info');
                log('- 性能采集器已启动', 'info');
                log('- 网络采集器已启动', 'info');
                log('- 行为采集器已启动', 'info');
                
                updateStatus();
            } catch (error) {
                log('SDK初始化失败: ' + error.message, 'error');
            }
        }

        // 获取状态
        function getStatus() {
            log('获取监控状态...', 'info');
            const status = {
                sessionId: 'session_' + Date.now(),
                userId: 'test_user',
                collectors: ['error', 'performance', 'network', 'behavior'],
                config: {
                    appId: 'test-app',
                    version: '1.0.0',
                    endpoint: 'https://monitor.test.com'
                }
            };
            log('监控状态: ' + JSON.stringify(status, null, 2), 'info');
        }

        // 切换调试模式
        function toggleDebug() {
            log('切换调试模式', 'info');
            log('调试模式已开启，将显示详细日志', 'success');
        }

        // 立即上报
        function flushData() {
            log('正在上报数据...', 'info');
            setTimeout(() => {
                log('数据上报完成！', 'success');
            }, 1000);
        }

        // 触发JS错误
        function triggerJSError() {
            log('触发JavaScript错误...', 'warning');
            try {
                // 故意触发错误
                undefinedFunction();
            } catch (error) {
                log('捕获到错误: ' + error.message, 'error');
            }
        }

        // 触发Promise错误
        function triggerPromiseError() {
            log('触发Promise错误...', 'warning');
            Promise.reject(new Error('测试Promise错误')).catch(error => {
                log('Promise错误: ' + error.message, 'error');
            });
        }

        // 触发资源错误
        function triggerResourceError() {
            log('触发资源加载错误...', 'warning');
            const img = new Image();
            img.onerror = () => log('图片加载失败', 'error');
            img.src = 'https://non-existent-image.jpg';
        }

        // 触发自定义错误
        function triggerCustomError() {
            log('触发自定义错误...', 'warning');
            const error = new Error('这是一个自定义测试错误');
            log('自定义错误: ' + error.message, 'error');
        }

        // 性能测量
        function measurePerformance() {
            log('开始性能测量...', 'info');
            performance.mark('test-start');
            
            // 模拟一些工作
            setTimeout(() => {
                performance.mark('test-end');
                performance.measure('test-duration', 'test-start', 'test-end');
                
                const measure = performance.getEntriesByName('test-duration')[0];
                log(`性能测量完成: ${measure.duration.toFixed(2)}ms`, 'success');
            }, 100);
        }

        // 模拟慢任务
        function simulateSlowTask() {
            log('模拟慢任务...', 'warning');
            const start = Date.now();
            
            // 阻塞主线程100ms
            while (Date.now() - start < 100) {
                // 空循环
            }
            
            log('慢任务完成，耗时: ' + (Date.now() - start) + 'ms', 'success');
        }

        // 获取Web Vitals
        function getWebVitals() {
            log('获取Web Vitals指标...', 'info');
            
            if ('performance' in window) {
                const navigation = performance.getEntriesByType('navigation')[0];
                if (navigation) {
                    log(`FCP: ${navigation.domContentLoadedEventEnd - navigation.fetchStart}ms`, 'info');
                    log(`LCP: ${navigation.loadEventEnd - navigation.fetchStart}ms`, 'info');
                }
            }
            
            log('Web Vitals获取完成', 'success');
        }

        // 内存测试
        function testMemoryUsage() {
            log('测试内存使用...', 'info');
            
            if ('memory' in performance) {
                const memory = performance.memory;
                log(`已用内存: ${(memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}MB`, 'info');
                log(`内存限制: ${(memory.jsHeapSizeLimit / 1024 / 1024).toFixed(2)}MB`, 'info');
            } else {
                log('浏览器不支持内存API', 'warning');
            }
        }

        // 测试Fetch请求
        function testFetch() {
            log('测试Fetch请求...', 'info');
            fetch('https://jsonplaceholder.typicode.com/posts/1')
                .then(response => response.json())
                .then(data => {
                    log('Fetch请求成功: ' + data.title, 'success');
                })
                .catch(error => {
                    log('Fetch请求失败: ' + error.message, 'error');
                });
        }

        // 测试XHR请求
        function testXHR() {
            log('测试XHR请求...', 'info');
            const xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/2');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const data = JSON.parse(xhr.responseText);
                    log('XHR请求成功: ' + data.title, 'success');
                } else {
                    log('XHR请求失败: ' + xhr.status, 'error');
                }
            };
            xhr.onerror = function() {
                log('XHR请求错误', 'error');
            };
            xhr.send();
        }

        // 测试慢请求
        function testSlowAPI() {
            log('测试慢请求...', 'warning');
            const start = Date.now();
            
            fetch('https://httpbin.org/delay/3')
                .then(response => {
                    const duration = Date.now() - start;
                    log(`慢请求完成，耗时: ${duration}ms`, 'success');
                })
                .catch(error => {
                    log('慢请求失败: ' + error.message, 'error');
                });
        }

        // 测试失败请求
        function testFailedAPI() {
            log('测试失败请求...', 'warning');
            fetch('https://httpbin.org/status/500')
                .then(response => {
                    log(`请求状态: ${response.status}`, response.ok ? 'success' : 'error');
                })
                .catch(error => {
                    log('请求失败: ' + error.message, 'error');
                });
        }

        // 跟踪点击
        function trackClick(element) {
            log('点击事件: ' + element.textContent, 'info');
        }

        // 跟踪输入
        function trackInput(element) {
            log('输入事件: ' + element.value, 'info');
        }

        // 跟踪业务事件
        function trackBusinessEvent() {
            log('跟踪业务事件: 用户购买', 'info');
            const eventData = {
                event: 'purchase',
                productId: 'prod_123',
                amount: 99.99,
                currency: 'CNY'
            };
            log('事件数据: ' + JSON.stringify(eventData), 'info');
        }

        // 跟踪用户行为
        function trackUserAction() {
            log('跟踪用户行为: 页面浏览', 'info');
            const actionData = {
                action: 'page_view',
                page: '/test',
                duration: 30000
            };
            log('行为数据: ' + JSON.stringify(actionData), 'info');
        }

        // 设置用户信息
        function setUserInfo() {
            log('设置用户信息...', 'info');
            const userId = 'user_' + Math.floor(Math.random() * 10000);
            log('用户ID已设置: ' + userId, 'success');
            document.getElementById('user-id').textContent = userId;
        }

        // 设置元数据
        function setMetadata() {
            log('设置元数据...', 'info');
            const metadata = {
                version: '2.0.0',
                feature: 'test-page',
                userType: 'tester'
            };
            log('元数据: ' + JSON.stringify(metadata), 'success');
        }

        // 清空输出
        function clearOutput() {
            document.getElementById('output').textContent = '';
            log('日志已清空', 'info');
        }

        // 导出日志
        function exportLogs() {
            const logs = document.getElementById('output').textContent;
            const blob = new Blob([logs], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'monitor-logs-' + new Date().toISOString().slice(0, 19) + '.txt';
            a.click();
            URL.revokeObjectURL(url);
            log('日志已导出', 'success');
        }

        // 页面加载完成后的初始化
        window.addEventListener('load', function() {
            log('🚀 Web Monitor SDK 测试页面加载完成', 'success');
            log('点击上方按钮开始测试各项功能', 'info');
            log('建议先点击"初始化SDK"按钮', 'warning');
        });

        // 监听错误事件
        window.addEventListener('error', function(event) {
            log('全局错误: ' + event.message, 'error');
        });

        // 监听Promise错误
        window.addEventListener('unhandledrejection', function(event) {
            log('未处理的Promise错误: ' + event.reason, 'error');
        });
    </script>
</body>
</html> 